package com.can.Demo01;

//基本的卖票例子

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 真正的多线程开发，公司中的开发，降低耦合性
 * 线程就是一个单独的资源类，没有任何附属的操作
 * 1.属性、方法
 */
public class SaleTicketLock {
    public static void main(String[] args) {
        //并发，多线程操作同一资源类,把资源类丢入线程
        Ticket2 ticket = new Ticket2();
        for (int i = 0; i < 60; i++) new Thread(ticket::sale,"A").start();

        for (int i = 0; i < 60; i++) new Thread(()->ticket.sale(),"B").start();

        for (int i = 0; i < 60; i++) new Thread(()->ticket.sale(),"C").start();

    }
}

//资源类 OOP
//lock三部曲
//1.new ReentrantLock();
//2.lock.lock();加锁
//3.finally=>lock.unlock();解锁
class Ticket2{
    //属性、方法
    private int number=50;

    Lock lock = new ReentrantLock();
    //卖票的方式
    public void sale(){
        lock.lock();
        lock.tryLock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票,剩余"+number);
            }
        }finally {
            lock.unlock();
        }

    }

}

